# -*- coding: utf-8 -*-

import os, logging
from functools import wraps
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users, app_identity
from datetime import datetime, timedelta
from google.appengine.ext import db
from google.appengine.api import memcache
from tsmodel import admin
#os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
#from google.appengine.dist import use_library
#use_library('django', '1.2')

APP_ID = app_identity.get_application_id()
imagesurl = ''#'http://gs.itiens.com'

def gmt_date(dt):
    return dt.strftime('%a, %d %b %Y %H:%M:%S GMT')

def requires_admin(method):
    @wraps(method)
    def wrapper(self, *args, **kwargs):
        if not self.islogin:
            return self.redirect(self.loginurl)#, federated_identity="https://www.google.com/a/itiens.com/o8/ud?be=o8"))
        elif (not self.isadmin) and (not self.adminacc):
            return self.redirect("/")
        else:
            return method(self, *args, **kwargs)
    return wrapper
def requires_auth(method):
    @wraps(method)
    def wrapper(self, *args, **kwargs):
        if not self.islogin:
            return self.redirect(self.loginurl)#, federated_identity="https://www.google.com/a/itiens.com/o8/ud?be=o8"))
        elif (not self.isadmin) and (not self.authacc):
            return self.redirect("/index")
        else:
            return method(self, *args, **kwargs)
    return wrapper

def authorized_ajax(method):
    @wraps(method)
    def wrapper(self, *args, **kwargs):
        if "X-Request-Method" not in self.request.headers:
            return self.error(403)
        elif self.request.headers["X-Request-Method"] != "XMLHttpRequest.aja$":
            return self.error(400)
        elif not self.islogin:
            self.response.set_status(302)
            return self.write(users.create_login_url('/'))
        elif (not self.isadmin) and (not self.authacc):
            self.response.set_status(302)
            return self.write(users.create_login_url('/'))
        else:
            return method(self, *args, **kwargs)
    return wrapper
def authadmin_ajax(method):
    @wraps(method)
    def wrapper(self, *args, **kwargs):
        if "X-Request-Method" not in self.request.headers:
            return self.error(403)
        elif self.request.headers["X-Request-Method"] != "XMLHttpRequest.aja$":
            return self.error(400)
        elif not self.islogin:
            self.response.set_status(302)
            return self.write(users.create_login_url('/'))
        elif (not self.isadmin) and (not self.adminacc):
            self.response.set_status(302)
            return self.write(users.create_login_url('/'))
        else:
            return method(self, *args, **kwargs)
    return wrapper

def pubdata(model=None, order=[], ttl=864000, reset=False):
    if model and model.kind():
        mkey = 'pub'+model.kind()+''.join(order)
        result = memcache.get(mkey)
        if (not result) or reset:
            result = model.all()
            for odr in order:
                result.order(odr)
            result = result.fetch(50)
            memcache.set(mkey, result, ttl)
    else:
        result = None
    return result

def getdata(model=None, filters=[], order=[], limit=20, ttl=86400, reset=False):
    if model:
        dkey = model.kind()
        if len(filters):
            for fltr in filters:
                dkey += fltr[0]+str(fltr[1])
        if order:
            dkey += "order"+ "".join(order)
        dkey += str(limit)

        result = memcache.get(dkey)
        if (not result) or reset:
            result = model.all()
            for odr in order:
                result.order(odr)
            for fltr in filters:
                result.filter(fltr[0], fltr[1])
            result = result.fetch(limit)
            memcache.set(dkey, result, ttl)
    else:
        result = None
    return result

class paging(object):
    def __init__(self, model=None, query=None, limit=10):
        if model:
            self.query = model.all()
        else:
            self.query = query

        self.limit = limit

    def fetch(self, pager):
        if hasattr(self.query,'__len__'):
            max_offset=len(self.query)
        else:
            max_offset = self.query.count()
        n = -(-max_offset / self.limit)

        if pager>n or pager<1:
            pager=1

        offset = (pager - 1) * self.limit
        if hasattr(self.query, 'fetch'):
            rkz = self.query.fetch(self.limit, offset)
        else:
            rkz = self.query[offset:offset+self.limit]

        return (max_offset, n, pager, rkz)

class baseHandler(webapp.RequestHandler):
    def initialize(self, request, response):
        webapp.RequestHandler.initialize(self, request, response)
        self.loginUser = users.get_current_user()
        self.islogin = (self.loginUser != None)
        self.isadmin = users.is_current_user_admin()
        self.loginurl = users.create_login_url(self.request.uri)
        self.logouturl = users.create_logout_url(self.request.uri)

        self.authacc = None
        if self.islogin:
            self.accEmail = self.loginUser.email()
            self.authacc = admin.all().filter('email =', self.accEmail.lower()).get()
        self.adminacc = None
        if self.authacc and self.authacc.isadmin:
            self.adminacc = self.authacc

    def render(self, template_file, values):
        path = os.path.join(os.path.dirname(__file__), template_file)
        self.response.out.write(template.render(path, values))

    def head(self, *args):
        return self.get(*args)

    def header(self, h, v):
        self.response.headers[str(h)] = str(v)

    def req(self, name, **kw):
        try:
            return self.request.get(name, **kw).strip()
        except:
            return self.request.get(name, **kw)

    def reqall(self, name, **kw):
        return self.request.get_all(name, **kw)

    def reqrate(self, name, **kw):
        return self.request.get_range(name, min_value=0, max_value=100, **kw)

    def reqint(self, name, default=0):
        try:
           return int(self.request.get(name))
        except:
           return default
    def reqallint(self, name, default=0):
        ra = self.request.get_all(name)
        for i in range(len(ra)):
            try:
                ra[i] = int(ra[i])
            except:
                ra[i] = default
        return ra

    def reqbool(self, name, default=False):
        try:
           return self.request.get(name)=='yes'
        except:
           return default

    def write(self, s):
        self.response.out.write(s)

    def writeJsTry(self, s):
        self.response.out.write("<script type='text/javascript'>try{%s}catch(e){}</script>" % s)

    def writeJs(self, s):
        self.response.out.write("<script type='text/javascript'>%s;</script>" % s)

